//
//  SearchController.m
//  万物记
//
//  Created by Ajen on 2019/6/21.
//  Copyright © 2019 Ajen. All rights reserved.
//

#import "SearchController.h"
#import "HomeContentCell.h"
#import "UITableView+RowsNumber.h"
#import "AddContentController.h"
@interface SearchController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIScrollViewDelegate>{
    NSMutableArray<LocalJsonModelAnything*> * anythingsMuArray;
    LocalJsonModel * searchResultModel;
    UILabel * hintLabel;
    NSInteger searchResultCount;
    NSString * oldSearchString;
    BOOL isEdit;
}
@property(nonatomic,strong)UITableView * tableView;
@property (weak, nonatomic) IBOutlet UITextField *inputView;
@property (weak, nonatomic) IBOutlet UIView *inputLine;

@end

@implementation SearchController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    anythingsMuArray = [NSMutableArray arrayWithCapacity:0];
    searchResultModel = [LocalJsonModel mj_objectWithKeyValues:@{}];
    
    UILabel * titleLabel = [UILabel new];
    titleLabel.aj_Text(@"搜索").aj_textColorHexStr(@"#2d2e36").aj_addToView(self.view);
    titleLabel.font = SongKeFont(23);
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20);
        make.top.equalTo(self.view).offset(STATUS_BAR_HEIGHT);
        make.height.equalTo(@44);
    }];
    self.navigationItem.titleView = titleLabel;
    
    self.inputView.delegate = self;
    
    hintLabel = [UILabel new];
    hintLabel.aj_Text(@"").aj_textAlignment(1).aj_textColorHexStr(@"#7a7374").aj_addToView(self.view);
    hintLabel.font = SongKeFont(15);
    [hintLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.inputLine.mas_bottom);
        make.height.equalTo(@44);
    }];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(hintLabel.mas_bottom);
    }];
    
    
    
}
- (IBAction)beginEdit:(id)sender {
    [UIView animateWithDuration:0.3 animations:^{
        self.inputLine.aj_bgColorHexStr(@"#2d2e36");
    }];
    
}

- (IBAction)endEdit:(id)sender {
    [UIView animateWithDuration:0.3 animations:^{
        self.inputLine.backgroundColor = [UIColor colorWithAjenHex:0x7a7374 alpha:0.2];
    }];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.inputView resignFirstResponder];
    if(!self.inputView.text.length){
        [self showMsg:@"还未输入任何关键字~"];
    }else{
        [self starSearchWithString:self.inputView.text];
    }
    return YES;
}

-(void)starSearchWithString:(NSString *)searchString{
    oldSearchString = searchString;
    searchResultCount = 0;
    [anythingsMuArray removeAllObjects];
    LocalJsonModel * allModel = [LocalModel shared].model;
    
    for(int tabIndex = 0 ; tabIndex < allModel.Anything.count ; tabIndex++){
        
        NSMutableArray<LocalJsonModelContentslist*> * contentsListMuArray = [NSMutableArray arrayWithCapacity:0];
        
        for(int listIndex = 0 ; listIndex < allModel.Anything[tabIndex].contentsList.count ; listIndex ++){
            
            if([allModel.Anything[tabIndex].contentsList[listIndex].title containsString:searchString]
               || [allModel.Anything[tabIndex].contentsList[listIndex].content containsString:searchString]){
                
                LocalJsonModelContentslist * listItem = [LocalJsonModelContentslist new];
                listItem = allModel.Anything[tabIndex].contentsList[listIndex];
                listItem.listIndex = listIndex;
                [contentsListMuArray addObject:listItem];
                searchResultCount ++;
            }
        }
        
        LocalJsonModelAnything * anythingItem = [LocalJsonModelAnything new];
        anythingItem.tabTitle = allModel.Anything[tabIndex].tabTitle;
        anythingItem.tabIndex = tabIndex;
        
        anythingItem.contentsList = contentsListMuArray;
        
        [anythingsMuArray addObject:anythingItem];
        
    }
    
    searchResultModel.Anything = anythingsMuArray;
    hintLabel.text = [NSString stringWithFormat:@"为您找到 %ld 条相关数据",searchResultCount];
    [self.tableView reloadData];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if(self.inputView.resignFirstResponder){
        [self.inputView resignFirstResponder];
    }
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(self.inputView.resignFirstResponder){
        [self.inputView resignFirstResponder];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return searchResultModel.Anything[section].contentsList.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return searchResultModel.Anything.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * bg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    bg.backgroundColor = [UIColor whiteColor];
    UIView * bg2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 44)];
    bg2.backgroundColor = [UIColor colorWithAjenHex:0x7a7374 alpha:0.05];
    [bg addSubview:bg2];
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, SCREEN_WIDTH-20, 44)];
    label.backgroundColor = [UIColor colorWithAjenHex:0x7a7374 alpha:0.05];
    label.text = [NSString stringWithFormat:@"%@",searchResultModel.Anything[section].tabTitle];
    
    label.textColor = [UIColor colorWithAjenHex:0xfbb612 alpha:1];
    label.font = [UIFont systemFontOfSize:17 weight:UIFontWeightBold];
    [bg addSubview:label];
    return bg;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier =@"HomeContentCell";
    HomeContentCell *cell = [tableView  dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell ==nil){
        cell = [[HomeContentCell alloc]initWithStyle:UITableViewCellStyleSubtitle  reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if(searchResultModel.Anything[indexPath.section].contentsList.count){
        cell.itemModel = searchResultModel.Anything[indexPath.section].contentsList[indexPath.row];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.inputView.resignFirstResponder){
        [self.inputView resignFirstResponder];
    }
    AJLog(@"%ld    %ld",searchResultModel.Anything[indexPath.section].tabIndex,searchResultModel.Anything[indexPath.section].contentsList[indexPath.row].listIndex);
    
    
    AddContentController * addContentController = [AddContentController new];
    addContentController.editItemModel = searchResultModel.Anything[indexPath.section].contentsList[indexPath.row];
    addContentController.editItemIndex = searchResultModel.Anything[indexPath.section].contentsList[indexPath.row].listIndex;
    addContentController.tabIndex = searchResultModel.Anything[indexPath.section].tabIndex;
    addContentController.successBlock = ^{
        [self starSearchWithString:oldSearchString];
        isEdit = YES;
    };
    addContentController.deleteBlock = ^(NSInteger deleteIndex) {
        [[LocalModel shared] deleteContentWithTabIndex:searchResultModel.Anything[indexPath.section].tabIndex andEditContentListIndex:searchResultModel.Anything[indexPath.section].contentsList[indexPath.row].listIndex];
        [self starSearchWithString:oldSearchString];
        isEdit = YES;
    };
    addContentController.moveToOtherTabBlock = ^{
        [self starSearchWithString:oldSearchString];
        //这里不用写,isEdit = YES; 因为编辑页面里面移动之后发送了通知
    };
    
    [self.navigationController pushViewController:addContentController animated:YES];
}




-(UITableView *)tableView{
    if(_tableView == nil){
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
        _tableView.delegate =self;
        _tableView.dataSource=self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorColor = [UIColor colorWithAjenHex:0x7a7374 alpha:0.2];
        _tableView.backgroundColor = [UIColor colorWithAjenHex:0xffffff alpha:0.9];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        UIView *tableViewHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, _tableView.bounds.size.width, CGFLOAT_MIN)];
        _tableView.tableHeaderView = tableViewHeaderView;
    }
    return _tableView;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if(isEdit){
        [[NSNotificationCenter defaultCenter] postNotificationName:@"REFRESH_HOME_TAB" object:nil userInfo:@{@"isEdit":@"YES"}];
    }
}
@end
